<template>
  <chart :options="options" :auto-resize="autoResize" :theme="theme" :watch-shallow="watchShallow"
         :class="className" :style="{height:height,width:width}"></chart>
</template>

<script>
  export default {
    props: {
      title: { type: String, default: '' },
      chartData: { type: Array },
      className: { type: String, default: 'chart' },
      theme: { type: String, default: 'macarons' },
      autoResize: { type: Boolean, default: true },
      watchShallow: { type: Boolean, default: true },
      width: { type: String, default: '100%' },
      height: { type: String, default: '250px' }
    },
    data() {
      return {
        options: this.buildOptions(this.chartData),
        barWidth: 25
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.options = this.buildOptions(val)
        }
      }
    },
    mounted() {
      if (!this.options && this.chartData) {
        this.options = this.buildOptions(this.chartData)
      }
    },
    methods: {
      buildOptions(chartData) {
        if (!chartData) {
          return
        }

        var legendData = ['metadata', 'hbase']
        var yAxisData = []
        var metadataData = []
        var hbaseData = []
        var max = 0
        var unit = ''
        chartData.map(item => {
          yAxisData.push(item.date)
          metadataData.push(item.metadata)
          hbaseData.push(item.hbase)
          max = max > Number(item.metadata + item.hbase).toFixed(2) ? max : Number(item.metadata + item.hbase).toFixed(2)
          unit = item.unit
        })

        var seriesData = [
          {
            name: 'metadata',
            type: 'bar',
            stack: '总量',
            barWidth: this.barWidth,
            label: {
              normal: {
                show: true,
                position: 'insideRight',
                formatter: '{c}' + unit
              }
            },
            data: metadataData
          },
          {
            name: 'hbase',
            type: 'bar',
            stack: '总量',
            barWidth: this.barWidth,
            label: {
              normal: {
                show: true,
                position: 'insideRight',
                formatter: '{c}' + unit
              }
            },
            data: hbaseData
          }
        ]

        return {
          legend: {
            data: legendData
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '0%',
            containLabel: true
          },
          xAxis: {
            show: false,
            type: 'value',
            max: max
          },
          yAxis: {
            show: true,
            type: 'category',
            data: yAxisData,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          series: seriesData
        }
      }
    }
  }
</script>
